<template>
<div ref="root" :style="style"></div>
</template>
<script setup>
  import { ref, watch, nextTick, onMounted, onUnmounted } from 'vue'
  import * as echarts from 'echarts'

  const props = defineProps(['option', 'style'])
  const root = ref()
  let charts

  const init = async () => {
    await nextTick()
    charts = echarts.init(root.value, {
      color: [
        '#0052d9',
        '#2ba471',
        '#e37318',
        '#d54941',
      ]
    })

    charts.setOption(props.option)
  }

  watch(() => props.option, () => charts.setOption(props.option))

  onMounted(() => {
    window.addEventListener('resize', () => charts.resize())
  })

  onUnmounted(() => {
    window.removeEventListener('resize', () => charts.resize())
  })

  const clear = () => charts.clear()

  defineExpose({ clear })
  init()
  </script>